//
//  FBTradeViewController.m
//  XTXOneToOne
//
//  Created by Canny on 2018/10/29.
//  Copyright © 2018年 WK. All rights reserved.
//

#import "FBTradeViewController.h"
#import "FBTradeModel.h"
#import "FBSlideView.h"
#import "FBTradeHeaderView.h"
#import "FBOrderListViewController.h"
#import "FBBugViewController.h"
#import "FBSaleViewController.h"


@interface FBTradeViewController ()<UIAlertViewDelegate>

@property (nonatomic,strong)FBTradeHeaderDataModel * headerModel;

@property (nonatomic,strong)FBSlideView * segmentView;

@property (nonatomic,strong)FBTradeHeaderView * headerView;

@property (nonatomic,assign)NSInteger page;

@property (nonatomic, strong) NSTimer *orderTimer;

@property (nonatomic, strong) UIAlertView *tipAlert;
@property (nonatomic, strong) UIAlertView *loginAlert;

@end

@implementation FBTradeViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    [self setProperty];
    
    [self createUI];
    
    
}

#pragma mark===========setProperty=============
-(void)setProperty{
    
    
    
    self.view.backgroundColor=RGB(231, 231, 231);
    
    _page = 1;
    
    [UIApplication sharedApplication].statusBarHidden = NO;
    
    self.navigationController.navigationBar.translucent = YES;
    self.navigationController.navigationBarHidden=YES;
    
}

-(void)createUI{
    
    FBTradeHeaderView * headerView = [[FBTradeHeaderView alloc]init];
    [self.view addSubview:headerView];
    headerView.frame=CGRectMake(0, 0, G_SCREENWIDTH, [FBTradeHeaderView computeHeight:@""]);
    _headerView = headerView;
    
    __weak __typeof(self)wself = self;

    _headerView.bugBlock = ^{
        [wself loadList:YES];
    };
    
    _headerView.saleBlock = ^{
        [wself loadList:YES];
    };
    
    _headerView.allOrderBlock = ^{
        NSString * token = [LoginModel GetValue:DL_token];
        if (token.length>0) {
            FBOrderListViewController * VC = [[FBOrderListViewController alloc]init];
            [wself.navigationController pushViewController:VC animated:YES];
            
        }else{
            [wself openLoginAlert];
        }
    };
}

-(void)loadData{
    
    NSString * URL = [NSString stringWithFormat:@"%@ex/data/dict",DEFAULTSEVERBASEURL];
    
    __weak __typeof(self)wself = self;
    [HUD showProgress:@"" inView:self.view];

    [MOLoadHttpsData GetHttpDataWithUrlStr:URL Dic:@{@"type":@"otc_currency"} SuccessBlock:^(id  _Nonnull responseObject) {
        
        NSDictionary * dic = responseObject;
        
        NSString * code = [NSString stringWithFormat:@"%@",dic[@"code"]];
        if ([code isEqualToString:@"0"]) {
            
            NSDictionary * dicc = dic[@"data"];
            wself.headerModel = [FBTradeHeaderDataModel  mj_objectWithKeyValues:dicc];
            if (wself.headerModel.otc_currency.count>0) {
                FBTradeModel * FBmodel = [FBTradeModel sharedFBTradeModel];
                FBmodel.selectedHeaderModel = wself.headerModel.otc_currency[0];
            }
            [wself createHeader];
            
            [wself loadList:YES];
        }
        
        
    } FailureBlock:^(id  _Nonnull error) {
 
        [HUD dismissInView:wself.view];

    }];
    
}


-(void)loadList:(BOOL)isNew{
    
    if (isNew) {
        _page = 1;
    }
    [HUD showProgress:@"" inView:self.view];
    NSString * URL = [NSString stringWithFormat:@"%@ex/otcbill/list",DEFAULTSEVERBASEURL];

    NSString * type;// @1：出售 @2:购买
    if (_headerView.Type == FBTradeHeaderType_Bug) {
        type=@"1";
    }else{
        type=@"2";
    }
    FBTradeModel * FBmodel = [FBTradeModel sharedFBTradeModel];
    NSDictionary * Dic  = @{
                            @"type":type,
                            @"currency":FBmodel.selectedHeaderModel.ID,//基础货币id
//                            @"legal_currency_id"
                            @"page":[NSString stringWithFormat:@"%ld",(long)_page],
                            @"limit":@"10"
                            };
    WS(weakSelf);
    [MOLoadHttpsData GetHttpDataWithUrlStr:URL Dic:Dic SuccessBlock:^(id  _Nonnull responseObject) {
        [HUD dismissInView:weakSelf.view];

        NSDictionary * dic = responseObject;

        NSString * code = [NSString stringWithFormat:@"%@",dic[@"code"]];
        if ([code isEqualToString:@"0"]) {
            
            NSDictionary * dicc = dic[@"data"];
            FBTradeModel * FBModel = [FBTradeModel sharedFBTradeModel];
            FBTradeOtcbListModel * ListModel =[FBTradeOtcbListModel mj_objectWithKeyValues:dicc];
            
            if (ListModel.list.count==0||ListModel.list.count<10) {
                weakSelf.segmentView.CollectionViewCell.tableView.mj_footer.hidden=YES;
            }else{
                weakSelf.segmentView.CollectionViewCell.tableView.mj_footer.hidden=NO;
            }
            if (isNew) {
                FBModel.ListModel = [[FBTradeOtcbListModel alloc]init];
                [FBModel.ListModel.list removeAllObjects];
            }
            [FBModel.ListModel.list addObjectsFromArray:ListModel.list];
//            NSLog(@"-------%@",FBModel.ListModel.list);
//            FBModel.ListModel = [FBTradeOtcbListModel mj_objectWithKeyValues:dicc];
           
            [weakSelf.segmentView.CollectionViewCell.tableView.mj_header  endRefreshing];
            [weakSelf.segmentView.CollectionViewCell.tableView.mj_footer  endRefreshing];
            
            
        }else{
            
            [weakSelf.segmentView.CollectionViewCell.tableView.mj_header  endRefreshing];
            [weakSelf.segmentView.CollectionViewCell.tableView.mj_footer  endRefreshing];
            weakSelf.segmentView.CollectionViewCell.tableView.mj_footer.hidden=YES;
        }
        
        
        [weakSelf.segmentView.CollectionViewCell relayOutUI];
        
        
    } FailureBlock:^(id  _Nonnull error) {
        
        [HUD dismissInView:weakSelf.view];

        
        
    }];
    
}


-(void)createHeader{
    
    NSArray * marr = self.headerModel.otc_currency;
    
    NSMutableArray * arr = [[NSMutableArray alloc]init];
    for (FBTradeHeaderModel * model in marr) {
        [arr addObject:model.symbol];
    }
    
    [_segmentView removeFromSuperview];
    _segmentView  =  [FBSlideView segmentControlViewWithFrame:CGRectMake(0, [FBTradeHeaderView computeHeight:@""], G_SCREENWIDTH, G_SCREENHEIGHT-[FBTradeHeaderView computeHeight:@""])];
    _segmentView.normalColor = RGB(102,102,102);
    _segmentView.selectedColor = MC_THEME_COLOR;
    _segmentView.SlideSelectedColor=MC_THEME_COLOR;
    _segmentView.titleArray = arr;
    _segmentView.selectedTitleArray = arr;
    
    [self.view addSubview:_segmentView];
    __weak __typeof(self)wself = self;
self.segmentView.CollectionViewCell.tableView.mj_footer.hidden=YES;

    _segmentView.block = ^(NSString * _Nonnull title) {
        FBTradeModel * FBModel = [FBTradeModel sharedFBTradeModel];
        [FBModel.ListModel.list removeAllObjects];
        for (FBTradeHeaderModel * Hmodel in wself.headerModel.otc_currency) {
            if ([Hmodel.symbol isEqualToString:title]) {
                FBModel.selectedHeaderModel=Hmodel;
            }
        }
        
        [wself loadList:YES];
        
    };
    
    _segmentView.rBlock = ^{
        wself.page++;
        [wself loadList:NO];
    };
    
    _segmentView.selectedBlock = ^(FBTradeOtcbillModel * _Nonnull model) {
        NSString * token = [LoginModel GetValue:DL_token];
        
        if (token.length>0) {
            [wself otcorderPreOrder:model];
        }else{
            [wself openLoginAlert];
        }
    };
}

#pragma mark-校验创建订单能力
-(void)otcorderPreOrder:(FBTradeOtcbillModel * )model{

    NSString * URL = [NSString stringWithFormat:@"%@otcorder/preOrder",DEFAULTSEVERBASEURL];
    
    NSDictionary * Dic  = @{
                            @"bill_sn":model.bill_sn,
                            @"access_token":[LoginModel GetValue:DL_token]
                            };
    WS(weakSelf);
    [HUD showProgress:@"" inView:self.view];
    [MOLoadHttpsData PostHttpDataWithUrlStr:URL Dic:Dic SuccessBlock:^(id  _Nonnull responseObject) {
        
        [HUD dismissInView:self.view];
        NSDictionary * dic = responseObject;
        
        NSString * code = [NSString stringWithFormat:@"%@",dic[@"code"]];
        NSString * msg = [NSString stringWithFormat:@"%@",dic[@"msg"]];
        if ([code isEqualToString:@"0"]) {
            
            if (weakSelf.headerView.Type==FBTradeHeaderType_Bug) {
                FBBugViewController * VC = [[FBBugViewController alloc]init];
                VC.dataSource = model;
                [weakSelf.navigationController pushViewController:VC animated:YES];
            }else{
                FBSaleViewController * VC = [[FBSaleViewController alloc]init];
                VC.dataSource = model;
                [weakSelf.navigationController pushViewController:VC animated:YES];
            }
        }else{
            [weakSelf openAlertTip:msg];
        }
        
        
    } FailureBlock:^(id  _Nonnull error) {
        [HUD dismissInView:self.view];

    }];
    
}

//
-(void)openAlertTip:(NSString *)title{
    
    _tipAlert = [[UIAlertView alloc] initWithTitle:@"提示" message:title delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    _tipAlert.delegate=self;
    _tipAlert.alertViewStyle = UIAlertViewStyleDefault;
    [_tipAlert show];
}

-(void)openLoginAlert{
    
    _loginAlert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请先登录" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    _loginAlert.delegate=self;
    _loginAlert.alertViewStyle = UIAlertViewStyleDefault;
    [_loginAlert show];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (alertView == _loginAlert) {
        if (buttonIndex == 1) { //确认
            LoginTool * LT = [LoginTool sharedLoginTool];
            LT.isGoToLogin=YES;
            self.tabBarController.selectedIndex = 3;
        }
    }
    

}

-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    
    [UIApplication sharedApplication].statusBarHidden = NO;
    self.navigationController.navigationBar.translucent = YES;
    self.navigationController.navigationBarHidden=YES;
    NSString * token = [LoginModel GetValue:DL_token];

    if (token.length>0) {
        [self setUpTimer];
    }



    [self loadData];
    
}

#pragma mark-创建定时器
- (void)setUpTimer{
    [self stopTimer];
    WS(wself);
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:6.0 target:wself selector:@selector(GetLatestOrderCount) userInfo:nil repeats:YES];
    self.orderTimer = timer;
    [[NSRunLoop mainRunLoop ] addTimer:timer forMode:NSRunLoopCommonModes];
    
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self stopTimer];
}

- (void)dealloc
{
    [self stopTimer];
}
- (void)stopTimer{
    //关闭定时器
    [self.orderTimer invalidate];
    
    self.orderTimer = nil;
    
}


#pragma mark-轮询
-(void)GetLatestOrderCount{

    
    NSString * URL = [NSString stringWithFormat:@"%@ex/otcorder/latestOrderCount",DEFAULTSEVERBASEURL];
    
   
//    FBTradeModel * FBmodel = [FBTradeModel sharedFBTradeModel];
    NSDictionary * Dic  = @{
                            
                            };
    WS(weakSelf);
    [MOLoadHttpsData GetHttpDataWithUrlStr:URL Dic:Dic SuccessBlock:^(id  _Nonnull responseObject) {
        [HUD dismissInView:weakSelf.view];
        
        NSDictionary * dic = responseObject;
        
        NSString * code = [NSString stringWithFormat:@"%@",dic[@"code"]];
        if ([code isEqualToString:@"905013"]||[code isEqualToString:@"0"]) {
            
            NSString * count =[NSString stringWithFormat:@"%@",dic[@"data"]];
            
            if ([count integerValue]>0) {
                weakSelf.headerView.num.text =count;
                weakSelf.headerView.num.hidden=NO;
            }else{
                weakSelf.headerView.num.hidden=YES;
            }
            
        }
    } FailureBlock:^(id  _Nonnull error) {
        
    }];
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
